package com.onpositive.wikitemplate;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class LocalTemplateStorage {
	
	private StringBuilder sBuilder = new StringBuilder() ;
	private String localTemplateStoragePath = "C:/wikistorage/templates/" ;
	
	public String load( String templateName, String subPath )
	{
		String result = null ;
		String filePath = createFilePath(templateName, subPath );
		File f = new File( filePath ) ;
		if( f.exists() && f.length() != 0 )
		try {
			int l = (int) f.length() ;
			FileInputStream fis = new FileInputStream(f) ;
			DataInputStream dis = new DataInputStream( fis );
			byte[] content = new byte[l] ;
			dis.readFully( content ) ;
			dis.close() ;
			fis.close() ;
			
			result = new String( content ) ;
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result ;
	}
	
	public void saveToLocalStorage( String templateName, String subPath,  String text )
	{
		String filePath = createFilePath( templateName, subPath );
		
		File dir = new File( localTemplateStoragePath ) ;
		dir.mkdirs() ;
		
		File f = new File( filePath ) ;
		
		try {
			f.createNewFile() ;
			FileOutputStream fos = new FileOutputStream(f) ;
			DataOutputStream dos = new DataOutputStream( fos );

			byte[] content = text.getBytes("UTF-8") ;
			int l = content.length ;
			dos.write( content ) ;
			dos.close() ;
			fos.close() ;
		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String createFilePath(String templateName, String subPath ) {
		
		prepareBuilder();
		
		sBuilder.append( ( localTemplateStoragePath + templateName.trim() ).replaceAll(" ", "_")  ) ;
		sBuilder.append( " doc" ) ;
		if( checkSubpathValidity(subPath) )
		{
			sBuilder.append( " " ) ;
			char ch = subPath.charAt(0);
			if( ch == '/' || ch == '\\' )
				sBuilder.append( subPath.substring(1) ) ;
			else
				sBuilder.append( subPath ) ;
		}
		sBuilder.append(".txt") ;
		
		return sBuilder.toString() ;
	}
	
	private void prepareBuilder() {
		if( sBuilder == null )
			sBuilder = new StringBuilder() ;
		else
			sBuilder.delete(0, sBuilder.length() ) ;
	}
	
	private boolean checkSubpathValidity(String subPath) {
		if( subPath.length() == 0 )
			return false ;
		
		return !( subPath.startsWith("/") || subPath.startsWith("\\") );
	}

}
